<?php

namespace App\Repositories\Eloquent;

use Illuminate\Container\Container as App;

use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;

use AlibabaCloud\Client\AlibabaCloud as AliCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

use App\Repositories\Eloquent\MemberRepository;
use Auth, Hash, DB, Session;

class UtilityRepository extends Repository
{    
    protected $member;

    public function __construct(App $app, MemberRepository $member)
    {
        parent::__construct($app);

        $this->member = $member;
    }


    public function model()
    {
        return 'App\Models\Utility';
    }


    /**
     * [验证码]
     * @return [type] [description]
     */
    public function captcha()
    {
        $phraseBuilder = new PhraseBuilder(4, '0123456789');

        $captcha = new CaptchaBuilder(null, $phraseBuilder);
        $captcha->setBackgroundColor(247, 247, 247);
        $captcha->setMaxBehindLines(0);
        $captcha->setMaxFrontLines(0);
        $captcha->build(110, 35);

        $phrase = $captcha->getphrase();

        Session::put('captcha', $phrase);
        header('Cache-Control: no-cache, must-revalidate');
        header('Content-type: image/jpeg');

        return $captcha->output();
    }


    public function sendSms($request)
    {

        $mobile = $request->mobile;

        if (empty($mobile) || strlen($mobile)!== 11) {
            return $this->responseFail(405, '手机格式不正确');
        }

        $option = array('PhoneNumbers' => $mobile,
                      'SignName'=>config('sms.sign'),
                      'TemplateCode' => config('sms.option.login.code'),
                      'TemplateParam' => json_encode( array('code'=>$this->smscode(true)) ) );

        $result = $this->send($option)->toArray();

        if( isset($result['Code']) && strcmp($result['Code'], 'OK') === 0)
            return $this->responseSuccess('验证码已发送', $result);
        
        return $this->responseFail(500, '验证码发送失败');
    }


    public function sendSmsRecruit($request)
    {
        $mobile = $request->mobile;

        if (empty($mobile) || strlen($mobile)!== 11) {
            return $this->responseFail(405, '手机格式不正确');
        }

        $isRegister = $this->member->findBy('mobile', $mobile);

        if( !empty($isRegister) )
            return $this->responseFail(403, '手机号码已注册');

        $option = array('PhoneNumbers' => $mobile,
                      'SignName'=>config('sms.sign'),
                      'TemplateCode' => config('sms.option.login.code'),
                      'TemplateParam' => json_encode( array('code'=>$this->smscode(true)) ) );

        $result = $this->send($option)->toArray();

        if( isset($result['Code']) && strcmp($result['Code'], 'OK') === 0)
            return $this->responseSuccess('验证码已发送', $result);
        
        return $this->responseFail(500, '验证码发送失败');
    }

    /**
     * 生成验证码
     * @return [type] [description]
     */
    protected function smscode($new = null)
    {
        if ($new) {
            $send = mt_rand(100000, 999999);

            Session::put('smscode', $send);
        } else {
            if (!Session::get('smscode')) {
                $send = mt_rand(100000, 999999);

                Session::put('smscode', $send);
            } else {
                $send = Session::get('smscode');
            }
        }

        return (string)$send;
    }
    
    /**
     * [二次验证安全码]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function safecode($request)
    {
        $safecode = $request->safecode;

        if ($safecode != SAFECODE) {
            return $this->responseFail(403, '安全码错误！');
        }

        return $this->responseSuccess('安全码正确', $safecode);
    }


    /**
     * 短信发送
     * @param  array  $option [description]
     * @return [type]         [description]
     */
    protected function send(array $option)
    {
        $query = array( 'RegionId' => config('sms.regionId') );
        
        if(isset($option)){
            $query = collect($query)->merge(collect($option));
        }
        $opt = array('query'=>$query->toArray());        

        AliCloud::accessKeyClient( config('sms.accessKey'), config('sms.accessSecret') )
            ->regionId(config('sms.regionId'))
            ->asDefaultClient();

        try {
            $result = AliCloud::rpc()
                ->product(config('sms.product'))
                ->version(config('sms.version'))
                ->action(config('sms.action'))
                ->method(config('sms.method'))
                ->host(config('sms.host'))
                ->options($opt)
                ->request();

            return $result;

        } catch (ClientException $e) {
            return $this->responseFail(500, '短信发送失败Client');

        } catch (ServerException $e) {
            return $this->responseFail(500, '短信发送失败Server');
        }
    }
}
